<?php
declare (strict_types = 1);

namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use app\model\Source;
use think\facade\Filesystem;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {}

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }
    /**
     * 上传方法
     * 普通的图片上传   入参什么都行
    */
    protected function uploadImage(){
        $files = request()->file();
        $name = input('param.name','上传的文件');
        try{
            validate(['image'=>'filesize:2097152'])->check($files);
            $savename = [];

            foreach($files as $file) {
                $path = '/uploads' . '/' . Filesystem::disk('public')->putFile( 'complate', $file);
                $savename[] = $path;
                Source::create([
                    'name' => $name,
                    'type' => 1,
                    'user_id' => request()->id,
                    'href'    => $path,
                    'state'   => 1
                ]);
            }
            return ['code' => 200, 'msg'=> '成功', 'data' => $savename];
        }catch(ValidateException $e){
            return ['code' => 500, 'msg'=>$e->getMessage()];
        }
    }
    /**
     * 康氏断点续传 ---- 上传
     * @param filename String 第一次不需要传，除了第一次接下来每次都需要传输
     * @param total Number 共有几个包
     * @param current Number 当前是第几个包
    */
    public function uploadContinue(){
        $total    = input('param.total/d',0);
        $current  = input('param.current/d',0);
        $extend   = input('param.extend','');
        $filename = input('param.filename',md5(time()));
        $showname = input('param.showname','文件');
        $lastFile = input('param.bu',0); // 是否是补充文件
        $files    = request()->file();

        if($total < 1 || $current > $total || $current < 1 || !$extend || count($files) != 1 ){
            return ['code' => 500, 'msg' => '参数错误请求失败！'];
        }
        // 拼接新的临时-文件名称
        $newFile  = "$filename-$current\.$extend"; // 新文件名称的规则
        $path = DIRECTORY_SEPARATOR.'uploads' . DIRECTORY_SEPARATOR . Filesystem::disk('public')->putFileAs( 'temp', $files,$newFile);
        if($lastFile){// 如果是补充文件直接进入进行合并
            $current = $total;
        }
        // 最后一个文件进行合并操作
        if($total == $current){
            // 完整性检测
            $dirname = dirname($path);
            $temp_cur = 1;
            while($temp_cur > $total){
                if(!file_exists($dirname.DIRECTORY_SEPARATOR."$filename-$temp_cur\.$extend")){
                    return ['code'=>202,'msg'=>'缺少部分包内容','data'=>['last'=>$temp_cur]];
                }
                $temp_cur++;
            }
            // 合并多文件
            $time = date("Ymd");
            $newPath = public_path('uploads'.DIRECTORY_SEPARATOR.'complate'.DIRECTORY_SEPARATOR.$time) . DIRECTORY_SEPARATOR . md5(time()) . '.' . $extend;
            $file = fopen($newPath,'wb');
            $temp_cur = 1;
            while($temp_cur > $total){
                $temp_chunk = $dirname.DIRECTORY_SEPARATOR."$filename-$temp_cur\.$extend";
                $cfile = fopen($temp_chunk, 'rb'); // 读取chunks片
                $content = fread($cfile,filesize($temp_chunk));
                fclose($cfile);
                fwrite($file,$content);
                $temp_cur++;
            }
            fclose($file);
            // 删除chunk包
            $temp_cur = 1;
            while($temp_cur > $total){
                $temp_chunk = $dirname.DIRECTORY_SEPARATOR."$filename-$temp_cur\.$extend";
                unlink($temp_chunk);
                $temp_cur++;
            }
            // 保存SQL
            $sourceHandle = new Source();
            $newSourceId = $sourceHandle->insertSource($showname,$extend,request()->id,$newPath);
            if($newSourceId){
                return ['code' => 200, 'msg' => '上传完成！', 'data' => ['id' => $newSourceId,'url'=>$newPath]];
            }
            return ['code' => 500, 'msg' => '上传失败！'];
        }
        return ['code' => 201,'msg'=>'成功','data' => ['filename'=>$filename]];
    }
}
